package com.hqyj.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint(value = "/user/{param}")
public class UserWebSocket {
    private static Map<String,Session> map = new HashMap<>();

    @OnOpen
    public void onOpen(Session s, @PathParam("param") String param){
        if (map.size() > 0 && map.containsKey(param)){
            //告诉前端该账号重复登录
            map.get(param).getAsyncRemote().sendText("0");
        }else {
            //告诉前端该账号可以登录
            map.put(param,s);
            for(Session ss:map.values()){
                if (ss.isOpen()){
                    ss.getAsyncRemote().sendText(param);
                }
            }
        }
    }

    @OnClose
    public void onClose(Session s,@PathParam("param")String param){
        map.remove(param);
    }

    //接受客户端发送的消息
    @OnMessage
    public void onMessage(Session s,String msg) throws IOException {

    }

    //异常触发的事件
    @OnError
    public void onError(Session s,Throwable t){
        System.out.println(s.getId() + "出现异常" + t.getMessage());
    }
}
